<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class AuthMini
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $action = $request->route()->getName();
        if (in_array($action, $this->except)){

            return $next($request);
        }

        $role = $request->header('role');
        $openid = $request->header('openid');
        if (!$role || !$openid){
            return response()->json(['code'=>401, 'msg'=>'未登录']);
        }
        if ($role != 'teacher' && $role != 'student'){
            return response()->json(['code'=>402,'msg'=>'非法请求']);
        }

        if($role == 'teacher') {
            $user = \App\Models\TeacherModel::where('wx_id', $openid)->first();
            if(!$user){
                return response()->json(['code'=>401,'msg'=>'用户不存在']);
            }
            $request->merge(['teacherInfo' => $user]);
            $request->merge(['teacherId' => $user->id]);
        } else {
            $user = \App\Models\StudentModel::where('parent_wx_id', $openid)->first();
            if(!$user){
                return response()->json(['code'=>401,'msg'=>'用户不存在']);
            }
            $request->merge(['studentInfo' => $user]);
            $request->merge(['studentId' => $user->id]);
        }

        return $next($request);
    }

    private $except = [
        'MiniBindWX',
        'MiniLogin',
        'MiniTeacherList',
    ];
}
